<template>
  <div>
    <van-nav-bar title="每日头条 - 登录" />

    <!-- 整体表单组件 @submit自定义事件 -->
    <van-form @submit="onSubmit">
      <van-field v-model="user.mobile" name="mobile" label="手机号" clearable required placeholder="请输入手机号"
                 :rules="[{ required: true, message: '请填写手机号' },{ pattern, message: '请输入正确手机号' }]" />
      <van-field v-model="user.code" name="code" center clearable required label="短信验证码" placeholder="请输入短信验证码"
                 :rules="[{ required: true, message: '请填写验证码' },]">
        <template #button>
          <van-button size="small" type="primary" native-type="button" @click="onCheck">发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" :loading="isLoading" loading-text="登录中...">登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import Notify from '@/ui/Notify.js'
import { setToken } from '@/utils/token.js'
import { setStorage } from '@/utils/storage.js'
export default {
  name: 'Login',
  data() {
    return {
      user: {
        mobile: '19860789783',
        code: '246810' // 模拟验证码，246810(只能用这个)
      },
      pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      isLoading: false
    }
  },
  methods: {
    async onSubmit(values) {
      try {
        // 把按钮变为加载状态
        this.isLoading = true
        const { data: res } = await loginAPI(values)

        Notify({ type: 'success', message: '登录成功' })
        // 给浏览器添加token
        setToken(res.data.token)
        setStorage('refresh_token', res.data.refresh_token)
        // 把按钮变为加可点击状态
        this.isLoading = false
        // 成功登录页面跳转 写到最后一行，防止后面代码不执行
        // 成功登录后，如果有path（登录前的页面），跳转；否则跳转到(/layout/home)
        this.$router.replace({ path: '/layout/home' || this.$route.query.path })
      } catch (err) {
        Notify({ type: 'danger', message: '账号或验证码错误' })
        // 把按钮变为加可点击状态
        this.isLoading = false
      }
    },
    onCheck() {
      Notify({ type: 'primary', background: '#f3f2ee', color: '#1e1e1e', message: '验证码为：246810' })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
